#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>

sem_t plate, apple, orange;

int amount = 10;

void *father(void *p)
{
    while(amount--){
        sem_wait(&plate);
        printf("Father puts apple…\n");
        sem_post(&apple);
    } 
    return NULL;
}

void *mother(void *p)
{
    while(amount--){
        sem_wait(&plate);
        printf("Mother puts orange…\n");
        sem_post(&orange);
    }  
    return NULL;
}

void *son(void *p)
{
    while(1){
        sem_wait(&orange);
        printf("Son gets orange… \n");
        sem_post(&plate);
    }    
    return NULL;
}

void *daughter(void *p)
{
    while(1){
       sem_wait(&apple);
       printf("daughter gets apple… \n");
       sem_post(&plate);
    }  
    return NULL;
}

int main(void)
{
    sem_init(&plate, 0, 1);     
    sem_init(&apple, 0, 0);
    sem_init(&orange, 0, 0);
    pthread_t tid[4];
    pthread_create(&tid[0], NULL, father, NULL);
    pthread_create(&tid[1], NULL, mother, NULL);
    pthread_create(&tid[2], NULL, son, NULL);
    pthread_create(&tid[3], NULL, daughter, NULL);
    pthread_join(tid[0], NULL);
    sem_destroy(&plate);    
    sem_destroy(&apple);
    sem_destroy(&orange); 
}